class UserController < ApplicationController
  def login
    if session[:user]
      redirect_to :controller=>"project", :action=>"list"
    else
      render :action=>"login", :layout=>"login_layout"
    end
  end

  def logout
    session[:user] = nil
    session[:user_id] = nil
    session[:selected_project_id] = nil
    redirect_to :action=>"login"
  end

  def do_login
    login = params[:login]
    password = params[:password]
    user = User.find(:first, :conditions=>["username=? AND password=? and user_status=?", login, sha1(password), 'Active'])
    if user
      session[:user] = user
      session[:user_id] = user.id
      redirect_to :controller=>"project", :action=>"list"
    else
      redirect_to :action=>"login"
    end
  end

  def signup
    @word = ""
    render :action=>"signup", :layout=>"login_layout"
  end

  def profile
    @word = ""
    @user = User.find(session[:user].id)
    render :action=>"profile", :layout=>"blank_layout"
  end

  def editpassword
    @word = ""
    @user = User.find(session[:user].id)
    render :action=>"editpassword", :layout=>"blank_layout"
  end

  def saveprofile
    @user = User.find(session[:user].id)
    @user.update_attributes(params[:u])
    @user.save
    @word = "Done!"
    render :action=>"profile", :layout=>"blank_layout"
  end

  def savepassword
    @user = User.find(session[:user].id)
    if params[:password]==params[:confirm_password]
      @user.password = sha1(params[:password])
      @user.save
      @word = "Done!"
    else
      @word = "Password Mismatch!"
    end
    render :action=>"editpassword", :layout=>"blank_layout"
  end

  def do_signup
    word_array = Array.new
    user_count = User.count(:conditions=>["username=?", params[:u][:username]])
    @username = params[:u][:username]
    @register_code = params[:u][:register_code]
    @title = params[:u][:title]
    @firstname = params[:u][:firstname]
    @lastname = params[:u][:lastname]
    @tel = params[:u][:tel]
    @job_position = params[:u][:job_position]
    @office = params[:u][:office]
    if params[:u][:username].empty?
      word_array = word_array << "Username can not be blank"
    else
      if params[:u][:username].index(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i)==nil
        word_array = word_array << "Wrong Email(Username) format"
      end
    end
    if user_count!=0
      word_array = word_array << "Username Exists"
    end
    if params[:u][:password].empty?
      word_array = word_array << "Password can not be blank"
    end
    if params[:u][:password_confirmation].empty?
      word_array = word_array << "Confirmation Password can not be blank"
    end
    if params[:u][:password]!=params[:u][:password_confirmation]
      word_array = word_array << "Wrong Password Confirmation"
    end
    if params[:u][:register_code].empty?
      word_array = word_array << "Registration Code can not be blank"
    else
      rc = RegisterCode.find(:first, :conditions=>["code=?", params[:u][:register_code]])
      if rc
        if rc.limit==rc.total
          word_array = word_array << "Registration Code reach its limit"
        end
      else
        word_array = word_array << "Wrong Registration Code"
      end
    end
    if params[:u][:firstname].empty?
      word_array = word_array << "Firstname can not be blank "
    end
    if word_array.size==0
      user = User.new(params[:u])
      user.password = sha1(params[:u][:password])
      user.save
      rc = RegisterCode.find(:first, :conditions=>["code=?", params[:u][:register_code]])
      rc.total = rc.total+1
      rc.save
      @word = 'Create Successfully<br/>'
      render :action=>"signup", :layout=>"login_layout"
    else
      @word = word_array.join('<br/>')+'<br/>'
      render :action=>"signup", :layout=>"login_layout"
    end
  end

  def user_import_csv
    render :action=>"user_import_csv", :layout=>"blank_layout"
  end
  
  def do_import_csv
    csvdata = params['csv'].read
    name_row = Array.new
    code_row = Array.new
    converted_code_row = Array.new
    import_type = Array.new
    csvdata.each_with_index do |line,i|
#			line = line.to_utf8
			line2 = line
			line2 = line2.gsub("\r","")
			line2 = line2.gsub("\n","")
			line2 = line2.gsub('"','')
			cols = line2.split(',')
      if i==0
        name_row = cols
      elsif i==1
        code_row = cols
        converted_code_row,import_type = prepare_userstock_symbol(name_row, code_row)
      else
        if !cols[0].empty?
          begin
            if cols[0].include? "/"
              d_a = cols[0].split('/')
              cols[0] = "#{d_a[2]}-#{d_a[1]}-#{d_a[0]}"
            end
            trade_date = Date.parse(cols[0])
            cols.each_with_index do |c,j|
              if j>0
                st = UserStockTrade.find(:first, :conditions=>["user_stock_id=? AND trade_date=?", converted_code_row[j], trade_date])
                if !st
                  st = UserStockTrade.new
                  st.user_stock_id = converted_code_row[j]
                  st.trade_date = trade_date
                end
                if import_type[j]=='price'
                  if c.empty?

                  elsif c=='na'
                    st.price = nil
                    st.save
                  else
                    st.price = c
                    st.save
                  end
                elsif import_type[j]=='volumn'
                  if c.empty?

                  elsif c=='na'
                    st.volumn = nil
                    st.save
                  else
                    st.volumn = c
                    st.save
                  end
                else

                end
              end
            end
          rescue
          end
        end
      end
    end
    converted_code_row.each do |ccr|
      cal_daily(ccr)
    end
    redirect_to :controller=>:user_stocks
  end

  def prepare_userstock_symbol(name_row, code_row)
    converted_code_row = Array.new
    converted_code_row[0] = 0
    import_type = Array.new
    name_row.each_with_index do |n,i|
      stock_company = n
      stock_symbol = nil
      pre_symbol = code_row[i]
      if pre_symbol.include?('(V)') || pre_symbol.include?('(VO)')
        import_type[i] = 'volumn'
      else
        import_type[i] = 'price'
      end
#      pre_symbol = pre_symbol.gsub('Q:','')
      if pre_symbol.include? '('
        stock_symbol = pre_symbol[0..pre_symbol.index('(')-1]
      else
        stock_symbol = pre_symbol
      end
      stock_symbol = stock_symbol.upcase
      if i>0
        stock = UserStock.find(:first, :conditions=>["s_symbol=? AND user_id=?", stock_symbol, session[:user_id]])
        if !stock
          stock = UserStock.new
          stock.user_id = session[:user_id]
          stock.s_symbol = stock_symbol
          stock.detail = stock_company
          stock.save
        end
        converted_code_row[i] = stock.id
      end
    end
    return converted_code_row,import_type
  end

  def cal_daily(id)
    sts = UserStockTrade.find(:all, :conditions=>["user_stock_id=?", id], :order=>"trade_date")
    sts.each_with_index do |st,i|
      if i>=1
        today_price = st.price
        yesterday_price = sts[i-1].price
        if today_price
          if yesterday_price
            begin
              daily_return = (today_price - yesterday_price)/yesterday_price
              st.daily_return = daily_return
              st.save
            rescue
            end
          end
        end
      end
    end
  end

end
